package com.xxx.orderservice.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class MessageProducer {

    @Resource
    private StreamBridge streamBridge;

    /**
     * 发送普通消息
     */
    public boolean sendMessage(String message) {
        // 绑定名称，在application.yml的stream里定义
        String bindingName = "im-out";
        boolean result = streamBridge.send(bindingName, message);
        if(result) {
            log.info("MessageProducer send message success. message: " + message);
        } else {
            log.error("MessageProducer send message fail. message: " + message);
        }
        return result;
    }

    /**
     * 发送延时消息
     */
    public boolean sendDelayMessage(String message, int delayLevel) {
        Map<String, Object> headers = new HashMap<>();
        headers.put(MessageConst.PROPERTY_DELAY_TIME_LEVEL, delayLevel);    // 设置延时等级，例如：3 = 10s（取决于你的配置）
        boolean result = streamBridge.send("delay-out", MessageBuilder.withPayload(message).copyHeaders(headers).build());
        if(result) {
            log.info("MessageProducer send delay message success. message: " + message);
        } else {
            log.error("MessageProducer send delay message fail. message: " + message);
        }
        return result;
    }
}